<template>
  <div>
    <el-row>
      <el-col style="margin-top: 30px">
        <el-input
          v-model="search"
          style="width: 240px"
          placeholder="请输入药仓方案名"
        />
        <el-button style="margin-left: 20px" type="primary">搜索</el-button>
        <el-button style="margin-left: 20px" type="primary" @click="add"
          >添加药仓方案</el-button
        >
      </el-col>

      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="reactiveDrugWarehouseMRS"
          :stripe="true"
          :border="true"
          :fit="true"
        >
          <el-table-column
            prop="name"
            label="药仓配药方案名称"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="medicationtime"
            label="服药时间"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>

          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="auto"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="detail(scope.row)"
                >详情/编辑</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                style="color: red"
                @click="delBerbak(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageno"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pagesize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <!-- 详情/编辑 -->
      <el-dialog
        title="药仓配药详情/修改"
        v-model="dialogFormVisible"
        width="40%"
        :before-close="handleClose_ex"
      >
        <div>
          <span style="display: inline-block; margin-right: 25px">方案名</span>

          <el-input
            v-model="edit_name"
            style="width: 240px"
            placeholder="请输入药仓方案名"
          />
        </div>

        <div style="margin-top: 20px">
          <span style="display: inline-block; margin-right: 25px"
            >用药时间</span
          >
          <el-time-select
            v-model="edit_time"
            style="width: 180px"
            start="00:00"
            step="01:00"
            end="24:00"
            @change="text"
          />
        </div>

        <el-table
          class="box-table"
          :data="msg_info"
          :stripe="true"
          :border="true"
          :fit="true"
          style="margin-top: 20px"
        >
          <el-table-column
            prop="drugname"
            label="药品名称"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <!-- <el-input
                v-model="scope.row.drugname"
                placeholder="请输入药品名"
              ></el-input> -->

              <el-select
                v-model="scope.row.drugname"
                filterable
                remote
                reserve-keyword
                placeholder="请输入药品名"
                :remote-method="remoteMethod"
                :loading="loading"
                style="width: 240px"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="count"
            label="数量"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.count"
                placeholder="请输入数量"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
        <el-button link type="primary" size="small" @click="add_edit()"
          >新增药品</el-button
        >
        <el-button link type="primary" size="small" @click="baocun_edit()"
          >保存</el-button
        >
      </el-dialog>

      <!-- 添加药仓方案 -->
      <el-dialog
        v-model="dialogVisible_add"
        title="添加单一药仓方案"
        width="40%"
        :before-close="handleClose"
      >
        <el-form :model="form" label-position="right">
          <el-form-item label="方案名:" label-width="100px">
            <el-input v-model="form.name" style="width: 200px"></el-input>
          </el-form-item>
          <el-form-item label="服药时间" label-width="100px">
            <el-time-select
              v-model="form.medicationtime"
              style="width: 180px"
              start="00:00"
              step="01:00"
              end="24:00"
            />
          </el-form-item>
          <el-form-item
            v-for="(item, index) in form.medicationregimens"
            :key="index"
            :label="'药品 ' + (index + 1)"
            label-width="100px"
          >
            <div style="display: flex; flex-direction: column">
              <!-- <el-input
                v-model="item.drugname"
                placeholder="药品名"
                style="width: 200px"
              ></el-input> -->
              <el-select
                v-model="item.drugname"
                filterable
                remote
                reserve-keyword
                placeholder="请输入药品名"
                :remote-method="remoteMethod"
                :loading="loading"
                style="width: 240px"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <el-input
                v-model="item.count"
                placeholder="数量"
                style="width: 200px; margin-top: 10px"
              ></el-input>
              <el-input
                v-model="item.remark"
                placeholder="备注"
                style="width: 200px; margin-top: 10px"
              ></el-input>
            </div>
          </el-form-item>
          <el-button
            style="width: 20%; margin-left: 20%"
            type="primary"
            @click="addMedicationRegimen"
            >添加药品</el-button
          >
        </el-form>
        <el-button
          style="width: 20%; margin-left: 20%; margin-top: 20px"
          type="primary"
          @click="baocun_add"
          >保存</el-button
        >
      </el-dialog>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import apiService from "@/services/apiService";
import { v4 as uuidv4 } from "uuid";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";
import { message } from "@/utils/message";
import dayjs from "dayjs";

//表格数据
const currentPage = ref(1);

const search = ref("");

const reactiveDrugWarehouseMRS = reactive([
  {
    id: "1",
    name: "测试1",
    medicationtime: "09:00:00",
    remark: "测试备注",
    medicationregimen: [
      {
        drugid: "测试药品1",
        count: "1",
        remark: "测试"
      },
      {
        drugid: "测试药品2",
        count: "1",
        remark: "测试"
      }
    ]
  },
  {
    id: "22",
    name: "测试",
    medicationtime: "10:00:00",
    remark: "测试备注",
    medicationregimen: [
      {
        drugid: "测试药品3",
        count: "1",
        remark: "测试"
      },
      {
        drugid: "测试药品4",
        count: "1",
        remark: "测试"
      }
    ]
  }
]);
//获取现有的单一药仓数据
const pageno = ref(1); // 当前页数
const pagesize = ref(10); //一页几条
const Total = ref<number>(1); //总条数
const GetList = () => {
  const params = {
    msgid: "PagingFindDrugWarehouseMR",
    token: getToken().accessToken,
    seq: uuidv4(),
    body: {
      pageno: pageno.value,
      pagesize: pagesize.value,
      userid: null
    }
  };
  apiService
    .post("", params)
    .then((res: any) => {
      // 假设接口返回的数据为 res.data
      const responseData = res.data;
      // 清空现有数据
      reactiveDrugWarehouseMRS.splice(0);
      reactiveDrugWarehouseMRS.push(...res.data.body.drugwarehousemrs);
      Total.value = res.data.body.totalrecords;
      console.log("现有药仓方案:", reactiveDrugWarehouseMRS);
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};

// 监听页码变化
const handleCurrentChange = val => {
  pageno.value = val;
  console.log("未回复");
  GetList();
};

// 监听每页条数变化
const handleSizeChange = val => {
  pagesize.value = val;
};

//添加药仓方案
const dialogVisible_add = ref(false);
const form = reactive({
  name: "",
  medicationtime: "",
  medicationregimens: [
    // {
    //   drugname: "",
    // dtc:"",
    //   count: "",
    //   remark: ""
    // }
  ]
});
const add = () => {
  dialogVisible_add.value = true;
};
interface ListItem {
  value: string;
  label: string;
}

const list = ref<ListItem[]>([]);
const options = ref<ListItem[]>([]);
const loading = ref(false);
// 添加药品
const addMedicationRegimen = () => {
  form.medicationregimens.push({
    dtc: "", //药品id
    drugname: "",
    count: "",
    remark: ""
  });
};
//输入值发生变化时调用
const remoteMethod = (query: string) => {
  if (query) {
    loading.value = true;
    const params = {
      msgid: "GetDrugsByCondition",
      token: getToken().accessToken,
      seq: uuidv4(),
      body: {
        name: query
      }
    };

    apiService
      .post("", params)
      .then((res: any) => {
        console.log("模糊查询:", res.data);
        list.value = res.data.body.Drugs.map(item => {
          return { value: `${item.DisplayName}`, label: `${item.DisplayName}` };
        });
        console.log("当前药品数组:", list.value);
      })
      .catch(error => {
        console.error("Error fetching data:", error);
      });

    setTimeout(() => {
      loading.value = false;
      options.value = list.value.filter(item => {
        return item.label.toLowerCase().includes(query.toLowerCase());
      });
    }, 200);
  } else {
    options.value = [];
  }
};
//保存按钮
const baocun_add = () => {
  // console.log(form);
  if (
    form.name != "" &&
    form.medicationtime != "" &&
    form.medicationregimens != []
  ) {
    //处理药品数据
    form.medicationregimens.forEach(item => {
      // 利用split和slice方法获取drugname字段中#后面的部分
      let parts = item.drugname.split("#");
      if (parts.length > 1) {
        item.dtc = parts[1].trim();
        item.drugname = parts[0].trim(); // 删除#号及之后的数据
      } else {
        if (item.dtc == "") {
          item.dtc = ""; // 如果没有#，则dtc为空字符串
        } else {
          item.dtc = item.dtc;
        }
      }
    });
    const params = {
      msgid: "InsertDrugWarehouseMR",
      token: getToken().accessToken,
      seq: uuidv4(),
      body: {
        name: form.name,
        medicationtime: form.medicationtime,
        medicationregimens: form.medicationregimens
      }
    };

    apiService
      .post("", params)
      .then((res: any) => {
        console.log("药仓新增接口:", res.data);
        if (res.data.code == 200) {
          message("新增完成", { type: "success" });
          GetList();
          dialogVisible_add.value = false;
          (form.name = ""),
            (form.medicationtime = ""),
            (form.medicationregimens = []);
        }
      })
      .catch(error => {
        console.error("Error fetching data:", error);
      });
  } else {
    message("请填写完整信息", { type: "error" });
  }
};

//删除
const delBerbak = (row: any) => {
  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const params = {
        msgid: "RemoveDrugWarehouseMR",
        token: getToken().accessToken,
        seq: uuidv4(),
        body: {
          id: row.id
        }
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          GetList();
          ElMessage({
            type: "success",
            message: "删除成功"
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

//详情
const dialogFormVisible = ref(false);

//详情
const msg_info = ref<any>([]);
const edit_name = ref<any>("");
const edit_time = ref<any>("");
const edit_id = ref<any>("");
const detail = (row: any) => {
  console.log("详情", row);
  msg_info.value = row.MedicationRegimen;
  edit_name.value = row.name;
  edit_time.value = row.medicationtime;
  edit_id.value = row.id;
  dialogFormVisible.value = true;
};

const text = (value: string) => {
  console.log(edit_time.value);
};
//修改按钮保存
const baocun_edit = () => {
  console.log(msg_info.value);
  if (edit_name.value != '' && edit_time.value != '' && msg_info.value != []) {
    
    //处理药品数据
  msg_info.value.forEach(item => {
    // 利用split和slice方法获取drugname字段中#后面的部分
    let parts = item.drugname.split("#");
    if (parts.length > 1) {
      item.dtc = parts[1].trim();
      item.drugname = parts[0].trim(); // 删除#号及之后的数据
    } else {
      if (item.dtc == "") {
        item.dtc = ""; // 如果没有#，则dtc为空字符串
      } else {
        item.dtc = item.dtc;
      }
    }
  });

  const params = {
    msgid: "UpdateDrugWarehouseMRByID",
    token: getToken().accessToken,
    seq: uuidv4(),
    body: {
      id: edit_id.value,
      name: edit_name.value,
      medicationtime: edit_time.value,
      medicationregimens: msg_info.value
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      console.log("药仓修改接口:", res.data);
      if (res.data.code == 200) {
        message("修改完成", { type: "success" });
        GetList();
        dialogFormVisible.value = false;
      } else {
        message("请填写正确药品信息", { type: "error" });
      }
    })
    .catch(error => {
        console.error("Error fetching data:", error);
    });
  } else {
    message("请填写完整信息", { type: "error" });
  }
  
};
const add_edit = () => {
  msg_info.value.push({
    dtc: "", //药品id
    drugname: "",
    count: "",
    remark: ""
  });
  console.log(msg_info.value);
};

//关闭弹窗
const handleClose = (done: () => void) => {
  done();
  (form.name = ""), (form.medicationtime = ""), (form.medicationregimens = []);
};
const handleClose_ex = (done: () => void) => {
  console.log('关闭');
   GetList();
    msg_info.value = [];
  done();
  // (form.name = ""), (form.medicationtime = ""), (form.medicationregimens = []);
};

onMounted(async () => {
  GetList();
});
</script>

<style lang="scss" scoped>
.active-button {
  background-color: #409eff; /* 设置按钮激活时的背景颜色 */
  color: white; /* 设置按钮激活时的文字颜色 */
}
</style>
